<template>
	<div class="app-container">
		<div class="filter-container">
			<el-input v-model="listQuery.companyName" placeholder="公司名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
			<el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
			<el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
		</div>

		<el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
			<el-table-column label="职位ID" prop="id" align="center" width="65"></el-table-column>
			<el-table-column label="公司名称" prop="companyName" align="center"></el-table-column>
			<el-table-column label="公司规模" width="80px" prop="companyScale" align="center"></el-table-column>
            <el-table-column label="所在地" width="80px" prop="companyCity" align="center"></el-table-column>
			<el-table-column label="地址" prop="companyLocation" align="center" width="350"></el-table-column>
			<el-table-column label="添加日期" align="center">
				<template slot-scope="scope">
					<span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="success" @click="goToDetail(scope.row)">查看</el-button>
					<el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
					<el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handelDelete(scope.row)">{{ $t('table.delete') }}
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList"></pagination>

		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close='clearTemp'>
			<el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px">
				<el-form-item label="企业名称" prop="type">
					<el-input v-model="temp.companyName"/>
				</el-form-item>
                <el-form-item label="所在地" prop="title">
                    <el-select v-model="temp.companyCity" class="filter-item" placeholder="请选择" style="width: 100%">
                        <el-option v-for="item in cityList" :key="item.key" :label="item.value" :value="item.key" />
                    </el-select>
                </el-form-item>
				<el-form-item label="企业规模" prop="type">
					<el-input v-model="temp.companyScale"/>
				</el-form-item>
				<el-form-item label="是否热门" prop="type">
					<template>
						<el-radio v-model="temp.companyIsHot" label="0">是</el-radio>
						<el-radio v-model="temp.companyIsHot" label="1">否</el-radio>
					</template>
				</el-form-item>
				<el-form-item label="企业图片">
					<el-row>
						<!-- <el-col>
							<el-button type="primary" size="mini" @click="upload">点击上传</el-button>
								<div class="el-upload__tip">只能上传文件 JPG/PNG 格式，且图片大小不能超过2M</div>
							<input type="file" name="file" v-show="false" ref="uploadInput" @change="handleFile">
							<ul class="el-upload-list el-upload-list--text">
								<li tabindex="0" class="el-upload-list__item is-success" v-for="(item, index) in fileList">
									<a class="el-upload-list__item-name">
										<i class="el-icon-document"></i>
										{{item.name}}
									</a>
									<label class="el-upload-list__item-status-label">
										<i class="el-icon-upload-success el-icon-circle-check"></i>
									</label>
									<i class="el-icon-close" @click="deletePic(index)"></i>
									<i class="el-icon-close-tip">按 delete 键可删除</i>
								</li>
							</ul>
							<ul style="list-style: none;width: 100%;padding-start: 0;" class="clearfix" @mouseleave='leaveIndex'>
								<li v-for="(item, index) in picList" style="float: left;width: 150px;height: 150px;margin-right: 5px;position: relative;" @mouseover="changeOverIndex(index)">
									<img :src="item" style="max-width: 150px;max-height: 150px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">
									<div style="position: absolute;width: 100%;height: 100%;background: #5a51519c;" v-show='index === overInDex'>
										<i class="el-icon-delete picDelete" @click='deletePic(index)'></i>
									</div>
								</li>
							</ul>
						</el-col> -->
						<el-col>
							<!-- <el-upload class="upload-demo" :action="host+'/admin/img/1'" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture">
								<el-button size="small" type="primary">点击上传</el-button>
								<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
							</el-upload> -->
							<div class="el-upload__tip">只能上传文件 JPG/PNG 格式，且图片大小不能超过2M</div>
							<el-upload :action="host+'/admin/img/1'" list-type="picture-card" :on-remove="handleRemove" :limit="5" :headers="headers" :on-exceed="handleExceed" accept="image/png, image/jpeg" :on-success='handleSuccess' :file-list="fileList">
							  <i class="el-icon-plus"></i>
							</el-upload>
						</el-col>
					</el-row>
				</el-form-item>
				<el-form-item label="企业地址" prop="type">
					<el-input type="textarea" v-model="temp.companyLocation"/>
				</el-form-item>
				<el-form-item label="企业简介" prop="type">
					<el-input type="textarea" v-model="temp.companyDesc"/>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="clearTemp">清空</el-button>
				<el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
			</div>
		</el-dialog>

		<el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogDetailVisible">
			<el-form ref="detailForm" :rules="rules" :model="temp" label-position="right" label-width="100px">
				<el-form-item label="企业名称" prop="type">
					<span>{{temp.companyName}}</span>
				</el-form-item>
                <el-form-item label="所在地" prop="title">
                    <el-select v-model="temp.companyCity" class="filter-item" placeholder="请选择" style="width: 100%">
                        <el-option v-for="item in cityList" :key="item.key" :label="item.value" :value="item.key" />
                    </el-select>
                </el-form-item>
				<el-form-item label="企业规模" prop="type">
					<span>{{temp.companyScale}}</span>
				</el-form-item>
				<el-form-item label="是否热门" prop="type">
					<span>{{temp.companyIsHot | showText}}</span>
				</el-form-item>
				<el-form-item label="企业图片">
					<template>
						<ul style="list-style: none;">
							<li v-for="item in fileList" style="float: left;width: 150px;height: 150px;margin-right: 5px;">
								<img :src="item.url" style="max-width: 150px;max-height: 150px">
							</li>
						</ul>
					</template>
				</el-form-item>
				<el-form-item label="企业地址" prop="type">
					<span>{{temp.companyLocation}}</span>
				</el-form-item>
				<el-form-item label="企业简介" prop="type">
					<span>{{temp.companyDesc}}</span>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
	import {
		fetchEnterPriseListAjax,
		addEnterPriseAjax,
		updateEnterpirseAjax,
		delEnterpriseAjax
	} from "@/api/enterprise";
import waves from "@/directive/waves"; // Waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

const calendarTypeOptions = [
{ key: "CN", display_name: "China" },
{ key: "US", display_name: "USA" },
{ key: "JP", display_name: "Japan" },
{ key: "EU", display_name: "Eurozone" }
];

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
	acc[cur.key] = cur.display_name;
	return acc;
}, {});

export default {
	name: "ComplexTable",
	components: { Pagination },
	directives: { waves },
	filters: {
	},

	data() {
		return {
			tableKey: 0,
			list: [],
			total: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 10,
				companyName: '',
			},
			textMap: {
				create: "新增企业",
				detail: '企业信息',
				update: '编辑信息'
			},
            cityList:[
                {
                    key: '南京',
                        value: '南京'
                }, {
                    key: '昆山',
                        value: '昆山'
                }, {
                    key: '滁州',
                        value: '滁州'
                },
                {
                    key: '合肥',
                    value: '合肥'
                },
                {
                    key: '无锡',
                    value: '无锡'
                },
                {
                    key: '常州',
                    value: '常州'
                },
                {
                    key: '苏州',
                    value: '苏州'
                },
                {
                    key: '无锡',
                    value: '无锡'
                },
                {
                    key: '上海',
                    value: '上号'
                },
                {
                    key: '云南',
                    value: '云南'
                }
            ],
			calendarTypeOptions,
			downloadLoading: false,
			dialogFormVisible: false,
			temp: {},
			rules: {},
			fileList: [],
			dialogDetailVisible: false,
			dialogStatus: '',
			picList: [],
			overInDex: '',
			host: process.env.BASE_API,
			dialogVisible: true,
			dialogImageUrl:'',
			headers: { Authorization: 'Bearer ' + this.$store.state.user.token },
		};
	},
	created() {
		this.getList();
	},

	filters: {
		showText(val) {
			if(val == '0') {
				return '是'
			} else {
				return '否'
			}
		}
	},

	methods: {
		handleSuccess(file, fileList) {
			this.fileList.push({
				url: file.data.file
			})
		},

		handleRemove(file, fileList) {
			this.fileList = [];
			fileList.forEach((item) => {
				this.fileList.push(item);
			})
		},

		handleExceed(files, fileList) {
	        this.$message.warning(`最多上传5张照片`);
	    },

		async getList() {
			this.listLoading = true;
			try {
				const result = await fetchEnterPriseListAjax(this.listQuery);
				if(result.data.code == 0) {
					this.list = result.data.data.pageData;
					this.total = result.data.data.maxCount;
				}
				this.listLoading = false;
			} catch(err) {
				console.log(err);
				this.listLoading = false;
			}
		},

		handleFilter() {
			this.listQuery.pageNum = 1;
			this.getList();
		},

		handleCreate() {
			this.dialogStatus = "create";
			this.temp = {};
			this.fileList = [];
			this.picList = [];
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
		},

		handelDelete(row) {
			this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.handelDeleteAjax(row);
			})
		},

		async handelDeleteAjax(row) {
			this.listLoading = true;
			try {
				await delEnterpriseAjax(row);
				this.handleFilter();
				this.$message({
					type: 'success',
					message: '删除成功!'
				});
				this.listLoading = false;
			} catch(err) {
				console.log(err);
				this.listLoading = false;
			}
		},

		goToDetail(row) {
			this.dialogDetailVisible = true;
			this.dialogStatus = 'detail';
			this.temp = row;
			this.fileList = [];
			if(this.temp.pic1) {
				this.fileList.push({
					url: this.temp.pic1
				});
			}
			if(this.temp.pic2) {
				this.fileList.push({
					url: this.temp.pic2
				});
			}
			if(this.temp.pic3) {
				this.fileList.push({
					url: this.temp.pic3
				});
			}
			if(this.temp.pic4) {
				this.fileList.push({
					url: this.temp.pic4
				});
			}
			if(this.temp.pic5) {
				this.fileList.push({
					url: this.temp.pic5
				});
			}
		},

		async createData() {
			if(this.fileList.length < 1) {
				this.$message.warning(`请至少上传一张图片`);
				return;
			}
			this.listLoading = true;
			try {
				var formData = new FormData();
				this.fileList.forEach((item, index) => {
					var attr = 'pic' + (index + 1);
					formData.append(attr, item.url)
				});
				formData.append('companyName', this.temp.companyName);
                formData.append('companyCity', this.temp.companyCity);
				formData.append('companyScale', this.temp.companyScale);
				formData.append('companyIsHot', this.temp.companyIsHot);
				formData.append('companyLocation', this.temp.companyLocation);
				formData.append('companyDesc', this.temp.companyDesc);
				await addEnterPriseAjax(formData);
				this.handleFilter();
				this.dialogFormVisible = false;
				this.listLoading = false;
			} catch(err) {
				console.log(err);
				this.listLoading = false;
			}
		},

		handleUpdate(row) {
			this.dialogFormVisible = true;
			this.dialogStatus = 'update';
			this.temp = row;
			this.fileList = [];
			this.picList = [];
			if(this.temp.pic1) {
				this.fileList.push({
					url: this.temp.pic1
				});
				this.picList.push(this.temp.pic1);
			}
			if(this.temp.pic2) {
				this.fileList.push({
					url: this.temp.pic2
				});
				this.picList.push(this.temp.pic2);
			}
			if(this.temp.pic3) {
				this.fileList.push({
					url: this.temp.pic3
				});
				this.picList.push(this.temp.pic3);
			}
			if(this.temp.pic4) {
				this.fileList.push({
					url: this.temp.pic4
				});
				this.picList.push(this.temp.pic4);
			}
			if(this.temp.pic5) {
				this.fileList.push({
					url: this.temp.pic5
				});
				this.picList.push(this.temp.pic5);
			}
			this.temp.companyIsHot = this.temp.companyIsHot.toString();
		},

		async updateData() {
			if(this.fileList.length < 1) {
				this.$message.warning(`请至少上传一张图片`);
				return;
			}
			this.listLoading = true;
			debugger;
			try {
				for(var i = 0; i < 5; i++) {
					this.temp['pic' + (i + 1)] = '';
				}
				for(var i = 0; i < this.fileList.length; i++) {
					this.temp['pic' + (i + 1)] = this.fileList[i].url;
				}
				await updateEnterpirseAjax(this.temp);
				this.handleFilter();
				this.dialogFormVisible = false;
				this.listLoading = false;
			} catch(err) {
				console.log(err);
				this.listLoading = false;
			}
		},

		clearTemp() {
			this.temp = {};
			this.fileList = [];
			this.picList = [];
		},

		upload() {
			if(this.dialogStatus == 'update') {
				return;
			}
			if(this.fileList.length < 5) {
				this.$refs.uploadInput.click();
			} else {
				this.$message.error('最多上传5张');
			}
		},

		handleFile() {
			let file = this.$refs.uploadInput.files[this.$refs.uploadInput.files.length - 1];
			if(!file) {
				return;
			}
			if(file.type == 'image/jpeg' || file.type == 'image/png') {
				if(file.size > 1024 * 1024 * 2) {
					this.$message.error('图片大小不能超过2M');
					return;
				}
				this.fileList.push(file);
				var reader = new FileReader();
				reader.onload = data => {
					let res = data.target || data.srcElement;
					this.picList.push(res.result);
				};
				reader.readAsDataURL(file);
			} else {
				this.$message.error('只能上传文件 JPG/PNG 格式');
			}
		},

		deletePic(index) {
			if(this.dialogStatus == 'update') {
				return;
			}
			this.fileList.splice(index, 1);
			this.picList.splice(index, 1);
		},

		changeOverIndex(index) {
			if(this.dialogStatus == 'update') {
				return;
			}
			this.overInDex = index;
		},

		leaveIndex() {
			this.overInDex = '';
		}
	}
};
</script>
<style type="text/css" scoped>
.picDelete {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	font-size: 40px;
	color: #fff;
	cursor: pointer;
}
</style>
